<?php
// 抽奖大转盘
namespace app\interfaces\controller;

use think\Db;
use think\View;
use think\Request;
use think\Exception;
use app\interfaces\model\SignLog;
use app\interfaces\model\DrawWinner;

class Draw
{
    // 抽奖主页
    public function index()
    {

        halt($arrgt = explode(',',1));
        $user_id = Request::instance()->param('user_id');
        $giftList = Db::name('sign_info')->where(['status' => 1])->order('id', 'desc')->select()->toArray();
        $restaraunts = array_column($giftList, 'title');
        $cover = array_column($giftList, 'cover');
        $color = array_column($giftList, 'color');
        $data = Db::name('draw_number')->where('id', $user_id)->find();

        $view = new View();
        echo $view->fetch('',[
            'restaraunts' => json_encode($restaraunts),
            'cover'       => $cover,
            'color'       => json_encode($color),
            'times'       => $data['deal_time'] < date('Y-m-d') ? 3 : $data['number'],
            'total'       => Db::name('sign_log')->group('user_id')->count()
        ]);


    }

    public function rand_ss()
    {
        // 获取参数
        $user_id = Request::instance()->param('user_id');

        // 每次消耗积分
        $price = 1;

        // 获取当前积分
        $find = Db::name('member')->where('id', $user_id)->value('integral');

        // 生成积分记录
        Db::name('integral_record')->insert([
           'member_id' => $user_id,
           'type_id'   => 2,
           'type'      => '兑换',
           'integral'  => $price,
           'title'     => '参加抽奖',
           'create_time' => time(),
        ]);

        // 如果积分不足
        if ($find < $price) {
            $data['status'] = '0';
            $data['rand'] = 0;
            $data['title'] = '您的积分不足!!';
            return json($data);
        }

        // 开始抽奖逻辑
        $giftList = Db::name('sign_info')->where(['status' => 1])->order('id', 'desc')->select();

        $total = Db::name('sign_info')->where(['status' => 1])->order('id', 'desc')->sum('inventory');

        Db::name('member')->where('id', $user_id)->setDec('integral', $price);
        $rand = 0;

        //概率数组的总概率精度
        //概率数组循环
        foreach ($giftList as $key => $value) {
            $randNum = mt_rand(1, $total);
            if ($randNum <= $value['inventory']) {
                $rand = $key;
                break;
            } else {
                $total -= $value['inventory'];
            }
        }

        if ($rand) {

            $data['status'] = 'y';
            $data['rand'] = $rand + 1;
            $data['title'] = '恭喜你获得：' . $giftList[$rand]['title'];

            $goods = Db::name('draw_goods')->where('id', $giftList[$rand]['good_id'])->find();
            // 如果中奖
            if ($goods) {

                // 生成中奖记录
                Db::name('draw_winner')->insert([
                    'member_id'   => $user_id,
                    'level'       => $rand + 1,
                    'goods_id'    => $giftList[$rand]['good_id'],
                    'picUrl'      => $goods['picUrl'],
                    'create_time' => time(),
                    'title'       => $goods['title'],
                ]);

                Db::name('sign_log')->insert([
                    'user_id'     => $user_id,
                    'gift_id'     => $giftList[$rand]['id'],
                    'create_time' => date('Y-m-d H:i:s',time())
                ]);
            }


        } else {
            $data['status'] = 'n';
            $data['title'] = '抽奖失败';
        }

        return json($data);

    }


    // 平台抽奖记录
    public function log(SignLog $log)
    {
        $data = $log
            ->alias('a')
            ->join('draw_number u', 'a.user_id=u.id', 'left')
            ->join('sign_info g', 'a.gift_id=g.id', 'left')
            ->field('a.*,u.unionid, DATE_FORMAT(create_time, "%Y-%m-%d") as create_time, u.name, g.title')
            ->order('create_time', 'desc')
            ->select();

        $view = new View();

        echo $view->fetch('',[
           'data' => $data,
        ]);
    }


    // 中奖记录
    public function order_list()
    {
        // 获取参数
        $user_id = Request::instance()->param('user_id');
        $status = Request::instance()->param('status', 0);

        if (empty($user_id)) throw new Exception('not empty');

        // 实例化
        $model = new DrawWinner();

        // 获取数据
        $ini = ['member_id' => $user_id, 'status' => $status];
        $data = $model->where($ini)->paginate(10);

        return ['code' => 200, 'message' => 'OK', 'data' => $data];

    }


    // 记录详情
    public function detail()
    {
        // 获取参数
        $order_id = Request::instance()->param('order_id');

        if (empty($order_id)) throw new Exception('not empty');

        $model = new DrawWinner();

        // 查询详情
        $item = $model->where('id', $order_id)->find();

        return ['code' => 200, 'message' => 'OK', 'item' => $item];
    }


    // 用户兑奖
    public function generating_order()
    {
        // 获取数据
        $order_id = Request::instance()->param('order_id');
        $address_name = Request::instance()->param('address_name');
        $address_phone = Request::instance()->param('address_phone');
        $address_area = Request::instance()->param('address_area');
        $address_site = Request::instance()->param('address_site');

        if (empty($order_id) || empty($address_name) || empty($address_phone) || empty($address_area) || empty($address_site)) throw new Exception('not Empty');

        $model = new DrawWinner();

        // 生成数组
        $con = [
            'name'  => $address_name,
            'phone' => $address_phone,
            'area_info'  => $address_area,
            'address'  => $address_site,
            'status'   => 1,
            'create_time' => date('Y-m-d',time()),
        ];

        // 操作
        $operation = $model->allowField(true)->save($con, ['id' => $order_id]);

        if ($operation) {
            return ['code' => 200, 'message' => 'Ok'];
        }
        return ['code' => 400, 'message' => 'Not Found'];

    }


    // 确认收货
    public function confirmation()
    {
        // 获取参数
        $order_id = Request::instance()->param('order_id');

        if (empty($order_id)) throw new Exception('not Empty');

        // 实例化
        $model = new DrawWinner();

        // 操作
        $operation = $model->allowField(true)->save(['status' => 2], ['id' => $order_id]);

        if ($operation) {
            return ['code' => 200, 'message' => 'Ok'];
        }
        return ['code' => 400, 'message' => 'Not Found'];

    }
}